const express = require('express')
const router = express.Router()
const models = require('../../models')
const Op = models.Sequelize.Op
const { success, error } = require('../../utils/message')
const checkPermission = require('../../middlewares/check-permission');

router.get('/', checkPermission(), async function (req, res, next) {
  const where = {}
  const status = req.query.status
  const outTradeNo = req.query.outTradeNo
  const currentPage = parseInt(req.query.currentPage) || 1
  const pageSize = parseInt(req.query.pageSize) || 10

  // 筛选订单状态
  if (status) {
    where.status = {
      [Op.eq]: status
    }
  }

  // 订单号
  if (outTradeNo) {
    where.outTradeNo = {
      [Op.eq]: outTradeNo
    }
  }

  const result = await models.Order.findAndCountAll({
    order: [['id', 'DESC']],
    where: where,
    offset: (currentPage - 1) * pageSize,
    limit: pageSize,
    include: [
      {
        model: models.OrderProduct,
        as: 'products'
      },
      {
        model: models.OrderAddress,
        as: 'address'
      }
    ],
    distinct: true,
  })

  const data = {
    orders: result.rows,
    pagination: {
      currentPage: currentPage,
      pageSize: pageSize,
      total: result.count
    }
  }
  success(res, '查询成功', data)
})

// 查询当前记录
router.get('/:id', checkPermission(), async function (req, res, next) {
  const id = req.params.id

  const order = await models.Order.findOne({
    where: { id: id },
    include: [
      {
        model: models.OrderProduct,
        as: 'products'
      },
      {
        model: models.OrderAddress,
        as: 'address'
      },
      {
        model: models.Express,
        as: 'express'
      }
    ]
  })

  if (!order) {
    return error(res, '当前订单不存在')
  }

  success(res, '查询成功', { order })
})

// 配货
router.patch('/:id/picking', checkPermission(), async function (req, res, next) {
  const id = req.params.id
  const order = await models.Order.findByPk(id)

  if (order.status < 2) {
    return error(res, '订单还未支付')
  }

  // 修改订单状态
  await order.update({
    status: 3,
    pickedAt: new Date()
  })

  success(res, '配货成功', order)
})

// 发货
router.patch('/:id/shipping', checkPermission(), async function (req, res, next) {
  const id = req.params.id
  const order = await models.Order.findByPk(id)
  const status = order.status
  const expressId = req.body.expressId
  const expressNum = req.body.expressNum
  let message

  if (!expressId) {
    return error(res, '请选择快递')
  }

  if (!expressNum) {
    return error(res, '请填写快递单号')
  }

  if (order.status < 3) {
    return error(res, '订单还未配货')
  }

  // 快递信息
  const express = await models.Express.findByPk(expressId)

  // 修改订单状态
  await order.update({
    status: 4,
    shippedAt: new Date(),
    expressId: expressId,
    expressNum: expressNum
  })

  message = status == 3 ? '发货成功' : '修改快递单号成功'
  success(res, message, order)
})

// 完成
router.patch('/:id/finishing', checkPermission(), async function (req, res, next) {
  const id = req.params.id
  const order = await models.Order.findByPk(id)

  if (order.status < 4) {
    return error(res, '订单还未发货')
  }

  // 修改订单状态
  await order.update({
    status: 5,
    finishedAt: new Date()
  })

  success(res, '交易完成', order)
})


module.exports = router
